/**
 * 
 */
package chances.wechat.applet;

import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.List;


import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import chances.framework.ufs.UserDirectory;
import chances.framework.ufs.UserFile;
import chances.framework.ufs.UserFileSystem;
import chances.utils.ImageUtils;
import chances.wechat.entity.UserMedia;
import chances.wechat.entity.WechatUser;
import chances.wechat.service.UserMediaService;
import chances.wechat.service.WechatUserService;
import net.coobird.thumbnailator.Thumbnails;



/**
 * @author chenxx
 *
 */
@Service
public class AppletPhotoService {

	@Value("${applet.photoe.resource:/var/upload}")
	private Resource resource;

	@Autowired
	UserFileSystem userFileSystem;
	
	@Autowired
	UserMediaService userMediaService;
	
	@Autowired
	WechatUserService userService;
	
	static Logger logger = LoggerFactory.getLogger("mprogramLogger");
	
	public AppletResponse savePhoto(List<MultipartFile> files, String openId) throws IOException {
		AppletResponse result = new AppletResponse();
		if (null == files || files.size() < 1) {
			result.setStatus(401);
			result.setMessage("文件为空");
			return result;
		}
		
		WechatUser wechatUser = userService.getWechatUser(openId);
		if (null == wechatUser) {
			result.setStatus(402);
			result.setMessage("用户不存在！");
			return result;
		}
		UserDirectory userdirectory = userFileSystem.getUserDirectory(openId);
		OutputStream out = null;
		for (MultipartFile file : files) {
			
				String oriFilename = file.getOriginalFilename();
				String fileName = "/photo/src_" + oriFilename + ".jpg";
				UserFile userFile = userdirectory.getUserFile(fileName);
				UserFile uf = userdirectory.createUserFile("photo");
				logger.info("user:{},upload photo:{}",openId,fileName);
				if (!uf.getFile().exists()) {
					uf.getFile().mkdirs();
				}
				try{
					out = userFile.getOutputStream();
					out.write(file.getBytes());
					out.flush();
				} finally {
					IOUtils.closeQuietly(out);
				}
				
				String mediaId = openId+"_"+(int)(Math.random() * 10e5);
				if (userFile.exists()) {
					UserMedia userMedia = createUserMedia(wechatUser, fileName, userFile, mediaId);
					convert(userMedia, userFile);
				} else {
					result.setStatus(405);
					result.setMessage("源文件不存在");
				}
		}

		return result;

	}

	public void convert(final UserMedia media, UserFile userFile) throws MalformedURLException, IOException {
		int width = media.getWidth();
		int height = media.getHeight();
		if (width <= 0 || height <= 0) {
			return;
		}
		String msgId = "" + media.getMediaId();
		File aFile = new File(userFile.getAbsolutePath());
		File parent = aFile.getParentFile();
		File icon = new File(parent, "icon_" + msgId + ".jpg");
		File hd = new File(parent, "hd_" + msgId + ".jpg");
		//File sd = new File(parent, "sd_" + msgId + ".jpg");
		try {
			int iconSize = 250;
			if (width < height) {
				Thumbnails.of(aFile).sourceRegion(0, (int) (height - width) / 2, width, width).size(iconSize, iconSize)
						.outputFormat("jpg").toFile(icon);
			} else {
				Thumbnails.of(aFile).sourceRegion((int) (width - height) / 2, 0, height, height)
						.size(iconSize, iconSize).outputFormat("jpg").toFile(icon);
			}
			Thumbnails.of(aFile).size(1280, 720).outputFormat("jpg").toFile(hd);

		} catch (Exception e) {
		}
	}
	
	private UserMedia createUserMedia(WechatUser wechatUser, String fileName, UserFile userFile, String mediaId)
			throws IOException {
		UserMedia result = new UserMedia();
		result.setOpenId(wechatUser.getOpenId());
		result.setMediaId(mediaId);
		Dimension dim = ImageUtils.getDimension(userFile.getFile());
		result.setHeight(dim.height);
		result.setWidth(dim.width);
		result.setType("photo");
		result.setSource(fileName);
		result.setStatus(UserMedia.PHOTO_NO_AUDIT);
		result.setNickname(wechatUser.getNickname());
		this.userMediaService.insertMedia(result);
		return result;
	}
}
